package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"oceanLearn/common"
	"oceanLearn/models"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 获取Authorization header
		tokenString := context.GetHeader("Authorization")

		context.JSON(200, gin.H{
			"data":    tokenString,
			"message": "测试",
		})

		// validate token formate
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "权限不足x",
			})
			context.Abort()
			return
		}

		tokenString = tokenString[7:]

		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "权限不足",
			})
			context.Abort()
			return
		}

		userId := claims.UserId
		DB := common.GetDB()
		var user models.User
		DB.First(&user, userId)

		if userId == 0 {
			context.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "权限不足",
			})
			context.Abort()
			return
		}

		//用户存在 将user 存入上下文 context
		context.Set("user", user)

		context.Next()
	}
}
